package org.ourgrid.common.statistics.control;

import org.ourgrid.common.LoginResult;
import org.ourgrid.common.statistics.util.hibernate.HibernateUtil;
import org.ourgrid.peer.dao.statistics.LoginDAO;
import org.ourgrid.peer.dao.statistics.PeerDAO;
import org.ourgrid.peer.to.PeerUser;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;

public class LoginControl extends EntityControl {
	
	private static LoginControl instance = null;
	
	public static LoginControl getInstance() {
		if (instance == null) {
			instance = new LoginControl();
		}
		return instance;
	}
	
	protected LoginControl() {}
	
	public void login(PeerUser peerUser, LoginResult loginResult, ServiceManager serviceManager) {
		logger.enter();
		
		HibernateUtil.beginTransaction();
		
		try {
			serviceManager.getDAO(LoginDAO.class).login(peerUser, loginResult, serviceManager);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
	}
	
	public void localConsumerFailure(PeerUser user, ServiceManager serviceManager) {
		logger.enter();
		
		HibernateUtil.beginTransaction();

		try {
			serviceManager.getDAO(LoginDAO.class).localConsumerFailure(user);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
	}

	public void clearLogins(ServiceManager serviceManager) {
		logger.enter();
		
		HibernateUtil.beginTransaction();

		try {
			Long peerLastUptime = serviceManager.getDAO(PeerDAO.class).getPeerLastUptime(
					serviceManager.getContainerContext());
			if (peerLastUptime == null) {
				peerLastUptime = System.currentTimeMillis();
			}
			serviceManager.getDAO(LoginDAO.class).clearLogins(peerLastUptime);
			
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		logger.leave();
		
	}
	

}
